﻿CREATE PROCEDURE [ServiceEngine].[UnsubscribeFromEvent] 
	@EventName varchar(100),
	@CallbackURI varchar(200)
AS
BEGIN
	DECLARE @ErrorMessage NVARCHAR(4000);
	DECLARE @ErrorSeverity INT;
	DECLARE @ErrorState INT;
	Declare @EventID as uniqueidentifier

	BEGIN TRY
		BEGIN TRANSACTION
	
		Select  @EventID = EventID
		From	[ServiceEngine].[Events] e
		Where	e.[Name] = @EventName
		
		if (@EventID is not null) BEGIN

			Delete	[ServiceEngine].[EventRegistrations]
			where	EventID = @EventID
			and		CallbackURI = @CallbackURI
			
		END 

		delete	[ServiceEngine].[EventRegistrations]
		where	Expires <= GetDate()	

		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
		SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();

		BEGIN TRANSACTION

		RAISERROR (@ErrorMessage, 
				   @ErrorSeverity,
				   1);
	END CATCH
		
	RETURN
END


